package cn.ljw.mybatis;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import lombok.SneakyThrows;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

/**
 * @author 一朝风月
 * @date 2024/9/21 20:43
 * @Code 面向注解面向卿，终无解释再无你
 * @description 封装Mybatis的资源信息类,IO流读写类加载后读mapper接口然后实例原理一致
 */

public class Resources {
    //日志
    private static final Logger logger = LoggerFactory.getLogger(Resources.class);
    /**
     * 读取资源文件
     * @param resource
     * @return
     */
    @SneakyThrows
    public static Reader getResourceAsReader(String resource){
        return new InputStreamReader(getResourceAsStream(resource));
    }


 private static InputStream getResourceAsStream(String resource) {
    // 获取所有可用的类加载器
    ClassLoader[] classLoaders = getClassLoaders();

    // 遍历每个类加载器尝试获取资源流
    for (ClassLoader classLoader : classLoaders) {
        try {
            InputStream inputStream = classLoader.getResourceAsStream(resource);
            // 如果资源流不为空，则返回该流
            if (inputStream != null) {
                return inputStream;
            }
        } catch (Exception e) {
            //此处源码中为抛异常我用try catch
            // 捕获并记录任何可能发生的异常

           logger.warn ("Error loading resource: " + resource, e);

        }
    }

    // 如果所有类加载器都无法找到资源，则返回null
    return null;
}


    /**
     * 获取类加载器
     * @return ClassLoader[]
     */
    private static ClassLoader[] getClassLoaders(){
        return new ClassLoader[]{
                Thread.currentThread().getContextClassLoader(),
                Resources.class.getClassLoader(),
                ClassLoader.getSystemClassLoader()
        };
    }
}
